#include "const/oPreDefine.h"
#include "physics/oSensor.h"
#include "physics/oBody.h"

oSensor::oSensor(oBody* owner, b2Fixture* fixture):
_enable(true),
_owner(owner),
_fixture(fixture)
{ }

oSensor::~oSensor()
{
	oSensor::clear();
	_owner = nullptr;
	_fixture = nullptr;
}

void oSensor::add( oBody* body )
{
	_sensedBodies.push_back(body);
	if (bodyEnter != NULL)
	{
		bodyEnter(this, body);
	}
	body->retain();
}

void oSensor::remove( oBody* body )
{
	for (uint32 i = 0; i < _sensedBodies.size(); i++)
	{
		if (_sensedBodies[i] == body)
		{
			int last = _sensedBodies.size() - 1;
			if (i != last)
			{
				_sensedBodies[i] = _sensedBodies[last];
			}
			_sensedBodies.pop_back();
			if (bodyLeave != NULL)
			{
				bodyLeave(this, body);
			}
			body->release();
			break;
		}
	}
}

bool oSensor::contains( oBody* body )
{
	BOOST_FOREACH(oBody* item, _sensedBodies)
	{
		if (item == body)
		{
			return true;
		}
	}
	return false;
}

void oSensor::clear()
{
	BOOST_FOREACH(oBody* body, _sensedBodies)
	{
		body->release();
	}
	_sensedBodies.clear();
}

const vector<oBody*>& oSensor::getSensedBodies() const
{
	return _sensedBodies;
}

void oSensor::setEnable( bool enable )
{
	_enable = enable;
	if (!enable)
	{
		oSensor::clear();
	}
}

bool oSensor::getEnable() const
{
	return _enable;
}

void oSensor::setTag( uint32 tag )
{
	_tag = tag;
}

uint32 oSensor::getTag() const
{
	return _tag;
}

oBody* oSensor::getOwner() const
{
	return _owner;
}

b2Fixture* oSensor::getFixture() const
{
	return _fixture;
}

oSensor* oSensor::create( oBody* owner, b2Fixture* fixture )
{
	oSensor* sensor = new oSensor(owner, fixture);
	sensor->autorelease();
	return sensor;
}
